'use strict';
const db = uniCloud.database();
const favoritesCollection = db.collection('favorites');

exports.main = async (event, context) => {
	const { userId, courseId } = event;
	
	if (!userId || !courseId) {
		return {
			code: 1,
			message: '参数错误'
		};
	}
	
	try {
		// 查询是否已收藏
		const favorite = await favoritesCollection.where({
			userId,
			courseId
		}).get();
		
		if (favorite.data.length > 0) {
			// 已收藏，取消收藏
			await favoritesCollection.doc(favorite.data[0]._id).remove();
			return {
				code: 0,
				message: '取消收藏成功',
				isFavorite: false
			};
		} else {
			// 未收藏，添加收藏
			await favoritesCollection.add({
				userId,
				courseId,
				createTime: Date.now()
			});
			return {
				code: 0,
				message: '收藏成功',
				isFavorite: true
			};
		}
	} catch (error) {
		return {
			code: 1,
			message: '操作失败'
		};
	}
}; 